package auth_ctrl

import (
	"admin-system/internal/request"
	"admin-system/internal/service/auth_svc"
	"admin-system/pkg/error_code"
	"admin-system/pkg/response"
	"github.com/gin-gonic/gin"
	"log/slog"
	"strconv"
)

type MenuController struct {
	MenuService *auth_svc.MenuService
}

func NewMenuController(MenuService *auth_svc.MenuService) *MenuController {
	return &MenuController{
		MenuService: MenuService,
	}
}

// GetMenuList
// @Summary 获取菜单列表，根据角色ID获取菜单列表
// @Produce  json
func (m *MenuController) GetMenuList(c *gin.Context) {
	// 获取所有菜单列表
	menu, err := m.MenuService.GetMenuList(c, nil)
	if err != nil {
		slog.Any("获取菜单列表失败", err)
		response.Fail(c, error_code.ErrInternalServer, "获取菜单列表失败")
		return
	}
	response.Success(c, menu)
	return
}

// GetMenuListByRoles
// @Summary 获取菜单列表，根据角色ID获取菜单列表
// @Produce  json
func (m *MenuController) GetMenuListByRoles(c *gin.Context) {
	// 获取当前角色下的菜单
	roleIdAny, ok := c.Get("role_id")
	if !ok {
		slog.Any("获取菜单列表失败", "获取角色ID失败")
		response.Fail(c, error_code.ErrInternalServer, "获取菜单列表失败")
		return
	}
	roleId := roleIdAny.(int64)
	menuIds, err := m.MenuService.GetMenuIdsByRole(c, roleId)
	if err != nil {
		slog.Any("获取菜单列表失败", err)
		response.Fail(c, error_code.ErrInternalServer, "获取菜单列表失败")
		return
	}
	menu, err := m.MenuService.GetMenuList(c, menuIds)
	if err != nil {
		slog.Any("获取菜单列表失败", err)
		response.Fail(c, error_code.ErrInternalServer, "获取菜单列表失败")
		return
	}
	response.Success(c, menu)
	return
}

// SaveMenu
// @Summary 创建菜单
func (m *MenuController) SaveMenu(c *gin.Context) {
	var menuReq request.MenuRequest
	if err := c.ShouldBindJSON(&menuReq); err != nil {
		slog.Error("请求参数错误", err)
		response.Fail(c, error_code.ErrInvalidParams, "请求参数错误"+err.Error())
		return
	}
	// 参数验证成功 创建菜单
	menu, err := m.MenuService.SaveMenu(c, menuReq)
	if err != nil {
		if menuReq.ID == 0 {
			slog.Any("创建菜单失败", err)
			response.Fail(c, error_code.ErrInternalServer, "创建菜单失败")
			return
		} else {
			slog.Any("更新菜单失败", err)
			response.Fail(c, error_code.ErrInternalServer, "更新菜单失败")
			return
		}
	}
	response.Success(c, menu)
	return
}

// GetMenuByID
// @Summary 根据ID获取菜单
func (m *MenuController) GetMenuByID(c *gin.Context, menuId int64) {
	menu, err := m.MenuService.GetMenuByID(c, menuId)
	if err != nil {
		slog.Any("获取菜单失败", err)
		response.Fail(c, error_code.ErrInternalServer, "获取菜单失败")
		return
	}
	response.Success(c, menu)
	return
}

// DeleteMenu
// @Summary 删除菜单
func (m *MenuController) DeleteMenu(c *gin.Context) {
	// 删除菜单
	menuIdStr := c.Param("id")
	menuId, err := strconv.ParseInt(menuIdStr, 10, 64)
	if err != nil {
		response.Fail(c, error_code.ErrInvalidParams, "参数错误")
		return
	}
	if err := m.MenuService.DeleteMenu(c, menuId); err != nil {
		slog.Any("删除菜单失败", err)
		response.Fail(c, error_code.ErrInternalServer, "删除菜单失败")
		return
	}
	response.Success(c, "删除菜单成功")
	return
}
